Skip to content

Measure the whole chain, and fix the segment defect it uncovered - #413

Merged
SergioDemianLerner merged 10 commits into
mainfrom
census/whole-chain-measurement
Nov 24, 2026
Merged

SergioDemianLerner merged 10 commits into
mainfrom
census/whole-chain-measurement

Conversation

@SDL-A1

@SDL-A1 SDL-A1 commented Nov 23, 2026

Copy link
Copy Markdown
Collaborator

The whole-chain measurement campaign, its results, and the segment defect it uncovered. Seven commits, each standalone and in a deliberate order so the history bisects.

What was measured

A whole-chain re-execution — 9,429,718 blocks, 106 segments, 17.4 hours, every state root verified, both positive controls firing so a zero is a measurement rather than a silence.

The census goes from 9 rows to 28, plus three high-water marks. Thirteen windows this chain never entered, fifteen it occupies. Full results in docs/retroactive-guard-measurements.md.

The finding worth reading

EVM-045 — the three RSK opcodes — was reported as occupied, therefore unremovable: SWAPN executed once in 9.4 million blocks.

Locating it changed the answer. Mainnet #996,053 is a contract creation whose init code is 68 octets of transfer(address,uint256) calldata: somebody sent an ERC-20 transfer with an empty to, so the node executed the calldata as init code. Its first octet is 0xa9, which below iris300 is SWAPN, and the next octet is its operand — SWAPN 5 on an empty stack. The creation fails; the address holds no account to this day. Nobody ever used the opcode.

Replaying that block both ways gives an identical state root, gasUsed, paid fees and receipt set: with the opcode, 0xa9 underflows; without it, 0xa9 is OpcodeNotFound. Both are exceptional halts consuming all gas, and the EVM records which exception nowhere.

So EVM-045 is removable despite firing — a conclusion no count could reach, only a two-way replay. The fixture is crates/execution/tests/swapn_at_996053.rs.

The defect it uncovered

segbuild shared the node's BtcBlockCache, so segments were built against a cache warmed by earlier segments. The Bridge's deep walks were served from memory, those nodes never entered the window store, and a cold reader got None for a node the chain has — the §6.9d hazard, and the cause of #374's false divergence report.

Measured: 510,219 reads a segment could not serve, across 77 of 106 segments, in 133 blocks, every one a deep Bridge walk. The fix gives segbuild a private cache and clears it per segment; it costs 0.029% of the segment set and does not grow as segments get shorter. Refs #410.

Existing segments are not repaired by this, and 77 of them need repairing.

Tooling honesty

reexec_all lost its findings three ways on a stop — RAM-only gap list, a truncating File::create on resume, and RAM-only counters that would make a resumed run report its own segments as the whole chain. All three fixed, plus an external stop file, exit code 2 for a requested stop, and a tracing subscriber, the absence of which made the report's claim that occurrences were "logged at WARN" false.

The gap file is now named after the state file rather than merely placed beside it. The old derivation meant every run shared one segment-gaps.txt whatever --state said, which came within one condition of destroying an 18-hour, 510,219-row list.

Deliberately not done

BR-063 and BR-083 are not counted. The obvious site in each is not where the legacy behaviour is applied, so a counter there would report a confident zero that means nothing. EVM-041a is counted for its STATICCALL half only; the shift opcodes come from the spec selection, not a branch.

Four zeros that prove less than they look — EVM-023 (occupied on testnet), BR-061 (unreachable by construction), EVM-041a (half-sited), BV-110 (expected zero) — are flagged as such in the report rather than left to be misread.

One figure is not reconciled: EVM-023a reports 4,875 where the specification describes #3,307 as the single occurrence. The control fired, which is what validated the campaign, but the figure should not be cited until that is resolved.

Verification

Workspace typechecks with examples and tests; rustock-core 383 passed, rustock-execution 1,912 passed, zero failures. Includes origin/main merged in, with both sides of the two auto-merged consensus files verified present.

Follow-ups filed

#410 (this PR's fix), #411 (testnet segments), #412 (testnet re-execution). Testnet remains unmeasured, so every result here is the mainnet half.

🤖 Generated with Claude Code

SergioDemianLerner and others added 10 commits November 23, 2026 16:27
…placed

The doc comment credited BYZANTIUM with STATICCALL from genesis and put the
shift opcodes and CREATE2 at papyrus200. Both are contradicted by the code in
the same file: rsk_instructions::install replaces STATICCALL with the
invalid-opcode handler below orchid under RSKIP-91, and upgrade_to_spec_id maps
wasabi100 onward to PETERSBURG precisely because wasabi enables the RSKIP-120
shifts and RSKIP-125 CREATE2.

Wrong in the direction a re-implementer would copy, which is why it is worth
fixing rather than deleting: the table reads as a specification of what is
available at each height. It now says the SpecId is an aside and the RSKIP
gates are what bind, and records what the table used to claim so the next
reader does not re-derive it.

Reported as D-003 against the specification project.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
A segment must contain every trie node a cold replay of its range reads.
segbuild shared the node's BtcBlockCache, so the Bridge's deep walks -- a
peg-in's confirmation count, a pegout's UTXO selection -- were served from a
cache warmed by earlier segments. Those nodes were never read, never promoted
into the window store, and never sealed. The segment was complete only for a
reader whose cache happened to be warm the same way; a cold reader got None for
a node the chain has, which is the 6.9d hazard and the cause of #374's false
divergence report.

Measured over the whole chain: 510,219 reads a segment could not serve, across
77 of 106 segments, in 133 blocks, every one of them a deep Bridge walk.

Private rather than merely cleared, because clear() on the shared Arc would
wipe the live node's cache at every segment boundary while it syncs. ~2 MB at
the default 10,000 entries. Clearing rather than disabling, because the cache
still pays for itself within a range and a disabled cache would make the build
read a superset of what any replay needs.

The nodes this adds are exactly the ones the measurement found missing: ~6,486
per affected segment, ~48.6 MB over the set, 0.029% of 161 GB. It does not grow
as segments get shorter -- the cost attaches to blocks, not to segments.

Existing segments are not repaired by this. Validation is a replay with no
fallback: one with a fallback cannot test it, because the archive silently
covers every hole.

Refs #410

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
The census moves from rustock-execution to rustock-core, because the BV-* and
BP-* rows live in core's validation code and core cannot depend on execution.
Re-exported from execution, so existing paths resolve unchanged.

Nineteen rows added, taking the registry from 9 to 28. Two groups matter:

  - all eight of the overflow-and-narrowing guards (BV-110, BV-125, BV-173,
    BR-061, BR-112, PC-042, EVM-062, PC-051). Unlike the rest these are
    monitoring rather than measurement: a non-zero is a live incident, and the
    specification is explicit that they should outlive the campaign.

  - EVM-023a, a second positive control. BR-086 proves a bridge counter can
    fire; this one names a single block and the exact figures it must produce
    (mainnet #3,307, 31,280 gas against a 30,000 limit), so it is the sharper
    test. It is asserted in the existing #3,307 regression rather than left to
    be discovered after an eleven-hour replay.

Several rows needed care about *where* rather than whether. BR-055 goes through
a counting wrapper so short-circuit evaluation attributes a marking to the
window only when the window caused it; EVM-043 counts the one arm that actually
differs from the standard rule; BR-097 counts both the singular and plural
receive paths, since batched submission is the normal case; EVM-023a is counted
on all four precompile arms, not just the Bridge's, because OutOfGas fires only
when required > limit and the rest are overcharged identically.

BR-063 and BR-083 are deliberately NOT counted. The obvious site in each is not
where the legacy behaviour is applied -- BR-063's else branch yields no reject
reason at all, and BR-083's is an early return guarding the new format -- so a
counter there would report a confident zero that means nothing.

vm_extremes records maxima rather than counts: deepest CALL-family frame, most
EVM memory expanded, largest RETURN payload. Each is packed with the block that
set it into one atomic, so a single fetch_max orders by value and carries the
block with no lock and no torn pair. Every quantity fits in 32 bits, and values
at or above 2^32 clamp rather than wrap so a clamp is obvious.

Both are off by default and switched on by the measuring tool, so a node
carries the call sites and none of the work. Runtime rather than a cargo
feature on purpose: features unify across a workspace build, so an example
asking for `census` would silently switch it on in the node binary built
beside it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
A seventeen-hour replay that loses its findings on a stop is not a tool, and
this one lost them three ways at once.

  - The gap list lived only in memory until the scheduler drained its queue, so
    a kill dropped it. It is now appended after every finished segment, which
    also keeps the in-memory list small enough that GAP_KEY_LIMIT is never
    reached. The cap rose from 50,000 to 2,000,000 regardless: the whole-chain
    run found 510,219 reads and recorded 9.8% of them.

  - File::create truncated the list, so a resumed run destroyed the previous
    run's findings. It appends, and truncates only on a genuinely fresh run.

  - The census counters lived only in memory too, so a resumed run would report
    its own segments' totals as the whole chain's -- a known-occupied control
    reading zero, which looks exactly like a clean window. They are banked per
    segment and reloaded on resume, and the run says out loud when it could not
    reload them.

The gap file is now named after the state file rather than merely placed beside
it. Deriving it from the parent directory meant every run on this machine
shared one segment-gaps.txt whatever --state said, so a second run with a fresh
state file would truncate the first's repair list. On 2026-11-23 that came
within one condition of destroying an 18-hour, 510,219-row list, and survived
only because the state file happened to be pre-seeded.

Stopping is now external and graceful: touch <state>.stop and it finishes the
segments in flight, banks them, and exits 2 -- not 1, because a requested stop
is not a failure and a script needs to tell them apart. Findings are banked
before a segment is marked done, so an interruption between the two replays a
segment rather than marking one done whose findings were lost.

Two reporting defects went with it. There was no tracing subscriber at all, so
the line claiming occurrences were "logged at WARN" was false -- a whole-chain
run found one SWAPN and could not say which block it was in. And the positive
controls are now reported by name, because "the campaign failed" sends a reader
to the whole table where "EVM-023a reported 0" names one counter and one block.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
account_at reports one account's nonce and balance at a chosen block from a
single trie lookup, and reports an absent account as absent rather than as a
zero balance. The two are different facts and on this chain the distinction
carries weight: a precompile address exists from an activation onward whatever
its balance, and an empty account is kept rather than pruned.

contract_code answers the question every measurement raises next. When a
high-water mark, a census hit or a divergence points at an address, the state
tools say whether it exists and what it holds, and none of them say what it is.
This prints the code, the instruction count, RSK's 0xFC header if present, and
the PUSH4 constants from a linear decode that honours PUSH immediates -- so an
octet inside a push is never read as an opcode, the discipline opcode_census
uses and the reason a naive byte scan over-reports.

It also takes --sig 'token0()' and prints that signature's selector, which is
the point: a selector list identifies a contract only if the names behind it
are computed rather than recalled. That is what turned the 413 KB memory
high-water mark from a guess into an identification -- 29 of 33 PUSH4 constants
in that contract compute to the exact Uniswap V3 Pool ABI.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
…it changes nothing

The whole-chain run found exactly one SWAPN in 9,429,718 blocks, at mainnet
#996,053. It is not a contract using the opcode. The transaction is a contract
creation whose init code is 68 octets of transfer(address,uint256) calldata --
somebody sent an ERC-20 transfer with an empty `to`, so the node executed the
calldata as init code. Its first octet is 0xa9, which below iris300 is SWAPN,
and the octet after it is the operand: SWAPN 5 on an empty stack. The creation
fails and the address holds no account to this day.

So the window is occupied, and a count alone would have ended the matter there.
Replaying the block both ways says otherwise. With SWAPN installed, 0xa9
underflows -- an exceptional halt consuming all gas. With it replaced by the
invalid-opcode handler, 0xa9 is OpcodeNotFound -- also an exceptional halt
consuming all gas, and the EVM records which exception nowhere. Identical state
root, gasUsed, paid fees and receipts, both matching the recorded root.

EVM-045 is therefore removable on mainnet despite firing, which no count could
have shown.

The test seeds from the pre-RSKIP126 baseline rather than the parent header,
because headers below #1,591,000 declare Orchid-format roots that name no node
in a Unitrie store. Run it once as it stands and once with SWAPN replaced in
rsk_instructions::install: one instruction changes and nothing else. Moving
iris300 instead would also move RSKIP-218's REMASC recipient and RSKIP-174's
created-at-a-funded-address rule, either of which would shift the root for
reasons unrelated to SWAPN.

The report records the run's results in full: 28 counters, thirteen windows
this chain never entered, fifteen it occupies, the three high-water marks, four
zeros that prove less than they look, and one figure not yet reconciled.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
The move to rustock-core added the new path but did not record the old one's
deletion, leaving two copies of the census registry in the tree. The stale one
is declared by no `mod` statement so it compiled and did nothing, which is the
problem: a registry that exists twice is a registry someone edits the wrong
half of.

Belongs in the move commit; it is separate only because nothing here is pushed
yet and rewriting four commits to tidy one deletion is the worse trade.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
TrieStore::get answers Option, so a segbuild reader cannot tell a key that is
genuinely absent from the state -- a legitimate answer the consensus rules
branch on -- from a node this store never captured. Reading the second as the
first is unsound and silent, and it is asymmetric: only code that reads state
the builder never read can hit it, so it always looks like a regression in the
newer code.

That asymmetry made a replay of #374 look like a mainnet consensus divergence,
and on 2026-11-22 it made segment 026-3792187-3815755 present as a STATE ROOT
MISMATCH at #3,812,411 -- investigated for a day as a consensus bug before
being isolated as one missing node.

AbortOnMissingNode stops the run and names both explanations, saying plainly
that this is NOT evidence of a consensus bug and that a passing run of older
code is no control, because code that never performs the read is immune by
construction.

Verified on the real segment: replaying 026 with no fallback now aborts naming
node ab12d849e9d1ea716caca53b211e88b4c45f4eb04d9a58ec9c6bdb0b502dd8d2, which is
exactly the gap the whole-chain fallback run recorded independently at that
block. Two unrelated mechanisms, the same node.

No change to NodeRef::resolve, which has 46 non-test callers in consensus-path
trie code. The guarantee does not need one: a trie walk reaches a store only
through NodeRef::Hash(h), and a parent commits to its child's hash, so a node
named by a hash exists in the real trie by construction. A genuine absence is
NodeRef::Empty and never reaches the store at all.

Scoped to the replay path and documented as such. It must not sit behind a
deliberate presence probe -- snapshot.rs's `if store.get(h).is_none()` expects
misses and handles them, and this would turn that expectation into an abort.

Issue #398 also asked for negative-read markers in the segment format so a
reader could tell the two apart. That is unnecessary, as above, and the cost
would have been a format change invalidating every segment already built; the
reasoning is recorded on the issue.

Refs #398

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
A stack overflow in Url::origin() on nested blob: URLs. The advisory was
published after this branch was cut, so cargo-deny's advisories check started
failing on every branch at once, this one included -- it is not a consequence
of anything here, which touches neither Cargo.toml nor Cargo.lock otherwise.

A patch bump within the existing semver range: url 2.5.8 -> 2.5.9 and
form_urlencoded 1.2.2 -> 1.2.3. No [[package]] entry is added, so no new
dependency, no new build.rs and no new proc macro arrive with it. Workspace
typechecks with examples and tests, no warnings.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
@SDL-A1

SDL-A1 commented Nov 23, 2026

Copy link
Copy Markdown
Collaborator Author

Two commits added.

3dc341d fixes the CI failure. cargo-deny (advisories) was failing on RUSTSEC-2026-0592 — a stack overflow in Url::origin() on nested blob: URLs. The advisory was published after this branch was cut, so it started failing every branch at once; this one touches neither Cargo.toml nor Cargo.lock otherwise. Fixed by a patch bump inside the existing semver range (url 2.5.8 → 2.5.9, form_urlencoded 1.2.2 → 1.2.3). No [[package]] entry is added, so no new dependency, build script or proc macro arrives with it.

9c9975b closes #398's parts 2 and 3, which belong here: this PR already fixes the builder side of the segment defect, and that is the reader side.

A segment reader could not tell a key genuinely absent from the state from a node the segment never captured, and read the second as the first. AbortOnMissingNode stops the run and names both explanations, stating plainly that it is not evidence of a consensus bug and that a passing run of older code is no control.

Verified against the real segment: replaying 026-3792187-3815755 with no fallback now aborts naming node ab12d849…dd8d2, which is exactly the gap the 17-hour fallback run recorded independently at #3,812,411. Two unrelated mechanisms, the same node.

NodeRef::resolve is deliberately unchanged — 46 non-test callers in consensus-path trie code, and the guarantee does not need it: a walk reaches a store only through NodeRef::Hash(h), and a parent commits to its child's hash, so a node named by a hash exists in the real trie by construction. A genuine absence is NodeRef::Empty and never reaches the store.

#398's Part 1 (negative-read markers in the segment format) is dropped — unnecessary for the same reason, and it would have been a format change invalidating every segment already built. Reasoning recorded on the issue.

@SergioDemianLerner
SergioDemianLerner merged commit 31eb483 into main Nov 24, 2026
9 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants